/**
 * 
 */
package wsepForum.persistance;
import java.io.UnsupportedEncodingException;
import java.security.*;


/**
 * static class that encrypt a given text to a representation according to MD5 algorithm. the encoder is used mainly
 * for encryption of passwords and use every time a user wants to login and password checking is required.
 * the encoder's hash function for encryption is only one way, thus, it require to use it every time we need to check password.
 * @author Ofir Tam & Ori Ossmy
 */
public class MD5Encoder {

	
	/**
	 * the main function of the decoder. gets a given text and returns the encryption. the function uses
	 * the MessageDigest object from the java's security package for generating the MD5 algoritm.
	 * @param text - the text we want to encrypt (the password..)
	 * @return String - the chiper text
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @postCondition - the ouput String is the input string after converting it by MD5 algorithm.
	 */
	public static String EncryptString(String textToEncrypt) throws NoSuchAlgorithmException, UnsupportedEncodingException  {
		
		// init the MessageDigest object for encrypting the message and gets the MD5 singelton
		MessageDigest mdInstance;
		mdInstance = MessageDigest.getInstance("MD5");
		
		// break the test to a byte array according to "iso-8859-1" Charset
		byte[] md5hashArray = new byte[32];
		mdInstance.update(textToEncrypt.getBytes("iso-8859-1"), 0, textToEncrypt.length());
		
		// generate the encrypted code
		md5hashArray = mdInstance.digest();
		
		// return the encoded message after sending it to the ConvertToHex function
		String encryptedText = convertToHex(md5hashArray);
		return encryptedText;
	}
	
	
	
	/**
	 * function to convert the encrypted to hexadecimel string. gets the break encryption array of bytes and return
	 * an encrypted string. 
	 * @param data - the array of bytes of the encrypted code
	 * @return String - string of the encrypted code
	 */
	private static String convertToHex(byte[] encryptedArray) {
		
		// init the buffer for generating the encrypted string 
        StringBuffer sbEncryptBuffer = new StringBuffer();
        
        // go over all the byte array and converting to hexa
        for (int tIndex = 0; tIndex < encryptedArray.length; tIndex++) {
        	int halfbyte = (encryptedArray[tIndex] >>> 4) & 0x0F;
        	int two_halfs = 0;
        	
        	// append char after char to the buffer for the converstion
        	do {
	        	if ((0 <= halfbyte) && (halfbyte <= 9))
	        		sbEncryptBuffer.append((char) ('0' + halfbyte));
	            else
	            	sbEncryptBuffer.append((char) ('a' + (halfbyte - 10)));
	        	halfbyte = encryptedArray[tIndex] & 0x0F;
        	} while(two_halfs++ < 1);
        }
        
        // return the encrypted string
        return sbEncryptBuffer.toString();
    }
}
